<template>
  <div class="net_work_box">
    <el-dialog
      @close="handleClose(false)"
      @open="handleOpen"
      close-on-press-escape
      v-dialogDrag
      :title="isedit ? '编辑网关' : '添加网关'"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :visible="showDialog"
      width="750px"
    >
      <el-tabs v-model="activeName" :tab-position="tabPosition">
        <el-tab-pane name="first" label="详情">
          <el-form
            label-position="right"
            :model="deviceGroupForm"
            :rules="deviceGroupRules"
            ref="deviceGroupForm"
            size="mini"
            class="demo-ruleForm"
            label-width="30%"
          >
            <el-row :gutter="16" type="flex">
              <el-col :span="12">
                <el-form-item label="Token:" prop="token">
                  <el-input
                    :disabled="isedit"
                    v-model="deviceGroupForm.token"
                    placeholder="请输入Token"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="MAC地址:" prop="macAddress">
                  <el-input
                    v-model="deviceGroupForm.macAddress"
                    placeholder="请输入MAC地址"
                  ></el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="品牌:" prop="brand">
                  <el-input
                    v-model="deviceGroupForm.brand"
                    placeholder="请输入品牌"
                  >
                  </el-input>
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="网关类型:" prop="assetTypeToken">
                  <el-select
                    style="width: 100%"
                    v-model="deviceGroupForm.assetTypeToken"
                    placeholder="请选择网关类型"
                  >
                    <el-option
                      v-for="item in typeList"
                      :key="item.token"
                      :label="item.token"
                      :value="item.token"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="型号:" prop="model">
                  <el-input
                    v-model="deviceGroupForm.model"
                    placeholder="请输入型号"
                  >
                  </el-input>
                </el-form-item>
              </el-col> -->

              <el-col :span="12">
                <el-form-item label="IP地址:" prop="ip" ref="ipRef">
                  <!-- <el-input v-model="deviceGroupForm.ip" placeholder="请输入型号">
                  </el-input> -->
                  <ul
                    class="ipAdress"
                    :style="{
                      border: isIpAdressFocus ? '1px solid #409eff' : ''
                    }"
                  >
                    <li
                      v-for="(item, index) in deviceGroupForm.ip"
                      :key="index"
                    >
                      <input
                        @focus="isIpAdressFocus = true"
                        type="text"
                        @input="checkIpVal(item, index)"
                        @keyup="turnIpPOS(item, index, $event)"
                        v-model="item.value"
                        ref="ipInput"
                        @blur="setDefaultVal(item, 'ip', index)"
                      />
                      <div></div>
                    </li>
                  </ul>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="名称:" prop="name">
                  <el-input
                    v-model="deviceGroupForm.name"
                    placeholder="请输入名称"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12" >
                <el-form-item label="ID:" prop="id">
                  <el-input
                    v-model="deviceGroupForm.id"
                    placeholder="请输入ID"
                  ></el-input>
                </el-form-item>
              </el-col> -->

              <el-col :span="12">
                <el-form-item label="网关地址:" prop="gatewayAddress">
                  <ul
                    class="ipAdress"
                    :style="{
                      border: isGatFocus ? '1px solid #409eff' : ''
                    }"
                  >
                    <li
                      v-for="(SubnetItem,
                      index) in deviceGroupForm.gatewayAddress"
                      :key="index"
                    >
                      <input
                        @focus="isGatFocus = true"
                        type="text"
                        @input="checkIpVal(SubnetItem, index)"
                        @keyup="turnIpPOS(SubnetItem, index, $event)"
                        v-model="SubnetItem.value"
                        ref="ipInput"
                        @blur="
                          setDefaultVal(SubnetItem, 'gatewayAddress', index)
                        "
                      />
                      <div></div>
                    </li>
                  </ul>
                  <!-- <el-input
                    v-model="deviceGroupForm.gatewayAddress"
                    placeholder="请输入网关地址"
                  ></el-input> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="图像:" prop="imageUrl">
                  <div style="display: flex; justify-content: space-between">
                    <app-upload
                      tips=""
                      :is-resolution="true"
                      @subUploadSucceed="handleUploadSucceed"
                    />
                    <div class="imageHome" v-if="showImg">
                      <img
                        style="width: 100%; height: 100%"
                        v-if="deviceGroupForm.imageUrl"
                        :src="deviceGroupForm.imageUrl | filtersFileUrl()"
                        class="image-size"
                      />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="子网掩码:" prop="SubnetAdress">
                  <!-- <el-input v-model="deviceGroupForm.subnetMask"
                    placeholder="请输入子网掩码"></el-input> -->
                  <ul
                    class="ipAdress"
                    :style="{
                      border: isAdressFocus ? '1px solid #409eff' : ''
                    }"
                  >
                    <li
                      v-for="(SubnetItem,
                      index) in deviceGroupForm.SubnetAdress"
                      :key="index"
                    >
                      <input
                        @focus="isAdressFocus = true"
                        type="text"
                        @input="checkIpVal(SubnetItem, index)"
                        @keyup="turnIpPOS(SubnetItem, index, $event)"
                        v-model="SubnetItem.value"
                        ref="ipInput"
                        @blur="setDefaultVal(SubnetItem, 'SubnetAdress', index)"
                      />
                      <div></div>
                    </li>
                  </ul>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane name="second" label="元数据" prop="metadata">
          <metaData
            :editmetaData="editmetaData"
            :isedit="showDialog"
            @sendmetaDatas="sendmetaData"
            ref="metaDataRef"
          />
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer" v-if="isedit">
        <el-button size="mini" @click="handleClose(false)">取 消</el-button>
        <el-button
          v-permission="[3, 'button']"
          size="mini"
          type="primary"
          @click="submitForm('deviceGroupForm')"
          >确 定</el-button
        >
      </div>
      <div slot="footer" class="dialog-footer" v-if="!isedit">
        <el-button size="mini" @click="handleClose(false)">取 消</el-button>
        <el-button
          v-permission="[1, 'button']"
          size="mini"
          type="primary"
          @click="submitForm('deviceGroupForm')"
          :loading="btnLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
var validcodegateway = (rule, value, callback, errMsg) => {
  // 校验IP是否符合规则
  var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
  let newVal = value.map(item => item.value);
  newVal = newVal.join(".");
  console.log(newVal, "valuevalue");
  if (!reg.test(newVal)) {
    return callback(new Error(errMsg));
  } else {
    callback();
  }
};
import MetaData from "@/views/opensite/metaData.vue";
import AppUpload from "@/views/device/devicegroups/UploadImage.vue";
import { setAssetsList, putAssetsList } from "@/api/assets";
import { TOKEN_RULES } from "@/utils/local";
// var axios = require('axios');
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    token: {
      type: String,
      default: ""
    },
    isedit: {
      type: Boolean,
      default: false
    },
    editmetaData: {
      type: Object,
      default: () => {}
    },
    typeList: {
      type: Array,
      default: () => []
    }
  },
  components: {
    MetaData,
    AppUpload
  },
  computed: {},
  data() {
    return {
      btnLoading: false,
      activeName: "first",
      url: "",
      isAdressFocus: false,
      isIpAdressFocus: false,
      isGatFocus: false,
      tabPosition: "left",
      deviceGroupForm: {
        SubnetAdress: [
          {
            value: ""
          },
          {
            value: ""
          },
          {
            value: ""
          },
          {
            value: ""
          }
        ],
        gatewayAddress: [
          {
            value: ""
          },
          {
            value: ""
          },
          {
            value: ""
          },
          {
            value: ""
          }
        ],
        ip: [
          {
            value: ""
          },
          {
            value: ""
          },
          {
            value: ""
          },
          {
            value: ""
          }
        ],
        token: "",
        imageUrl: "",
        name: "",
        metadata: {}
      },
      deviceGroupRules: {
        token: TOKEN_RULES,
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        // id: [{ required: true, message: "请输入id", trigger: "blur" }],
        brand: [{ required: true, message: "请输入品牌", trigger: "blur" }],
        model: [{ required: true, message: "请输入型号", trigger: "blur" }],
        gatewayAddress: [
          { required: true, message: "请输入网关地址", trigger: "blur" },
          {
            validator: (rule, value, callback) =>
              validcodegateway(rule, value, callback, "请输入正确的网关地址"),
            trigger: "blur"
          }
        ],
        ip: [
          {
            required: true,
            message: "请输入ip地址",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) =>
              validcodegateway(rule, value, callback, "请输入正确的ip地址"),
            trigger: "blur"
          }
        ],
        SubnetAdress: [
          { required: true, message: "请输入子网掩码", trigger: "blur" },
          {
            validator: (rule, value, callback) =>
              validcodegateway(rule, value, callback, "请输入正确的子网掩码"),
            trigger: "blur"
          }
        ],
        ipAdress: [
          { required: true, message: "请输入ip地址", trigger: "blur" }
        ],
        macAddress: [
          { required: true, message: "请输入MAC地址", trigger: "blur" }
        ],
        subnetMask: [
          { required: true, message: "请输入子网掩码", trigger: "blur" }
        ],
        assetTypeToken: [
          { required: true, message: "请选择网关类型", trigger: "change" }
        ],
        imageUrl: [{ required: true, message: "请上传图片", trigger: "blur" }]
      },
      metaDataJson: {},
      newRoles: "",
      editedRoles: []
    };
  },
  mounted() {},
  computed: {
    showImg: function() {
      return this.deviceGroupForm.imageUrl != "";
    }
  },
  watch: {},
  methods: {
    // ip输入
    checkIpVal(item, index) {
      let self = this;
      //确保每个值都处于0-255
      let val = item.value;
      //当输入的是空格时，值赋为空
      val = val.trim();
      val = parseInt(val, 10);
      if (isNaN(val)) {
        val = "";
      } else {
        val = val < 0 ? 0 : val;
        val = val > 255 ? 255 : val;
      }
      item.value = val;
    },
    turnIpPOS(item, index, event) {
      let self = this;
      let e = event || window.event;
      //删除键把当前数据删除完毕后会跳转到前一个input，左一不做任何处理
      if (e.keyCode == 8) {
        let val = item.value;
        console.log(val);
        if (index == 0) {
        } else if (val == "") {
          self.$refs.ipInput[index - 1].focus();
        }
      }
      //右箭头、回车键、空格键、冒号均向右跳转，右一不做任何措施
      if (
        e.keyCode == 39 ||
        e.keyCode == 13 ||
        e.keyCode == 32 ||
        e.keyCode == 190 ||
        e.keyCode == 110
      ) {
        if (index == 3) {
        } else {
          self.$refs.ipInput[index + 1].focus();
        }
      }
    },
    setDefaultVal(item, typeKey, index) {
      const that = this;
      if (index == 3) {
        validcodegateway("", this.deviceGroupForm.ip, function(res) {
          that.$refs["deviceGroupForm"].validateField(typeKey);
        });
      }

      // ipRef
      this.isAdressFocus = false;
      this.isIpAdressFocus = false;
      this.isGatFocus = false;
      //当input失去焦点，而ip没有赋值时，会自动赋值为0
      let val = item.value;
      if (val == "") {
        item.value = "0";
      }
    },
    //弹窗打开执行操作
    handleOpen() {
      this.$nextTick(() => {
        this.$refs["deviceGroupForm"].clearValidate();
      });
    },
    // 弹窗关闭执行操作
    handleClose(isRefresh) {
      this.$emit("closeDialog", isRefresh);
      this.cancelEmpty();
      const val = [
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        }
      ];
      this.deviceGroupForm.ip = [
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        }
      ];
      this.deviceGroupForm.SubnetAdress = [
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        }
      ];
      this.deviceGroupForm.gatewayAddress = [
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        },
        {
          value: ""
        }
      ];
    },
    //取消清空数据
    cancelEmpty() {
      this.$emit("update:showDialog", false);
      this.deviceGroupForm = {
        token: "",
        imageUrl: "",
        name: "",
        description: "",
        metadata: {},
        roles: []
      };
      this.editedRoles = [];
      this.metaDataJson = {};
      this.$refs.metaDataRef.metaData = [];
    },
    // 提交
    submitForm(formName) {
      let that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.deviceGroupForm.SubnetAdress) {
            this.$msg("请输入子网掩码");
            return;
          }
          if (!this.deviceGroupForm.gatewayAddress) {
            this.$msg("请输入网关地址");
            return;
          }
          if (!this.deviceGroupForm.ip) {
            this.$msg("请输入ip");
            return;
          }
          let formData = {};
          formData = Object.assign({}, this.deviceGroupForm);
          formData.metadata = this.metaDataJson;
          formData.roles = this.editedRoles;
          // 转换IP格式
          const newList = [];
          this.deviceGroupForm.ip.forEach(item => {
            newList.push(item.value);
          });
          const str = newList.join(".");
          formData.ip = str;
          // 转换IP格式
          const newList2 = [];
          const newList3 = [];
          this.deviceGroupForm.SubnetAdress.forEach(item => {
            newList2.push(item.value);
          });
          this.deviceGroupForm.gatewayAddress.forEach(item => {
            newList3.push(item.value);
          });
          const str2 = newList2.join(".");
          const str3 = newList3.join(".");
          formData.subnetMask = str2;
          formData.gatewayAddress = str3;
          this.btnLoading = true;
          if (this.isedit) {
            putAssetsList(formData, this.token)
              .then(res => {
                this.$msg({
                  type: "success",
                  message: "操作成功!"
                });
                // this.showDialog = false;
                this.$emit("update:showDialog", false);
                this.handleClose(true);
              })
              .finally(f => {
                this.btnLoading = false;
              });
          } else {
            setAssetsList(formData)
              .then(res => {
                this.$msg({
                  type: "success",
                  message: "操作成功!"
                });
                this.$emit("update:showDialog", false);
                this.handleClose(true);
              })
              .finally(f => {
                this.btnLoading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    //元数据页回传
    sendmetaData(md) {
      this.metaDataJson = md;
    },

    onRoleDeleted(role) {
      let roles = this.editedRoles;
      let index = roles.indexOf(role);
      if (index !== -1) {
        roles.splice(index, 1);
      }
    },
    handleUploadSucceed(url) {
      this.deviceGroupForm.imageUrl = url;
    }
  }
};
</script>

<style lang="scss" scoped>
.net_work_box {
  /deep/ .el-row--flex {
    flex-wrap: wrap;
  }
  /deep/ .el-form-item__label {
    white-space: nowrap;
  }
  /deep/ .el-tabs__nav-wrap {
    overflow: inherit;
  }
  /deep/ .custom-upload .el-button--primary {
    /* height: 104px; */
    /* width: ; */
  }
  /deep/ .el-tabs--left .el-tabs__nav-wrap.is-left::after,
  .el-tabs--left .el-tabs__nav-wrap.is-right::after,
  .el-tabs--right .el-tabs__nav-wrap.is-left::after,
  .el-tabs--right .el-tabs__nav-wrap.is-right::after {
    height: 300px;
  }
}
.ipAdress {
  background-color: #fff;
  background-image: none;
  border-radius: 2px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  /* height: 27px; */
  /* padding: 0 0.90909rem; */
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
  display: flex;
  align-items: center;
  margin: 0;
  padding: 0;
}
.isAdressFocus {
  border: 1px solid #409eff;
}
.ipAdress li {
  position: relative;
  height: 27px;
  margin: 0;
  list-style: none;
}

ul[class="ipAdress"] input[type="text"] {
  border: none;
  width: 100%;
  height: 26px;
  text-align: center;
  background: transparent;
  color: #606266;
  font-size: 12px;
}

.ipAdress li div {
  position: absolute;
  /* bottom: 2px; */
  right: 0;
  border-radius: 50%;
  background: #c0c4cc;
  width: 2px;
  height: 2px;
  top: 50%;
  margin-top: -1px;
}

/*只需要3个div*/
.ipAdress li:last-child div {
  display: none;
}

/*取消掉默认的input focus状态*/
.ipAdress input:focus {
  outline: none;
}

.addbutton {
  background-color: #2680d2;
  color: #ffffff;
  position: absolute;
  right: 0px;
  top: 0px;
}
.el-icon-plus {
  color: #ffffff;
}
.div-inline {
  display: inline;
  background-color: #e4e4e4;
  padding: 2px;
  border: 1px #5a5e66 solid;
  line-height: 25px;
  white-space: nowrap;
  word-wrap: break-word;
}
.imageHome {
  /* padding: 5px 5px 5px 5px; */
  /* width: 49%; */
  /* height: 104px; */
  /* background: rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
  overflow: hidden;
  border-radius: 2px; */
  width: 104px;
  height: 104px;
  background: rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
  opacity: 1;
  border-radius: 2px;
  .image-size {
    /*background: #2E2E2E;*/
    /* border-radius: 50%; */
    display: flex;
  }
}
</style>
